﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Microsoft.Practices.Prism.Regions;
using Snowdreamist.Windows;

namespace Snowdreamist.Prism.Region
{
    public class TabControlRegionAdapter : RegionAdapterBase<TabControl>
    {
        public TabControlRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory) { }

        protected override void Adapt(IRegion region, TabControl regionTarget)
        {
            if (region == null)
                throw new ArgumentNullException("region");
            if (regionTarget == null)
                throw new ArgumentNullException("regionTarget");
            if (regionTarget.ItemsSource != null || BindingOperations.GetBinding(regionTarget, ItemsControl.ItemsSourceProperty) != null)
                throw new InvalidOperationException("TabControl's ItemSource has already set");
            if (regionTarget.Items.Count != 0)
                throw new InvalidOperationException("TabControl has already contained child items");
            // Only allow two kinds of types
            // 1. An object implements ITabRegionViewModel
            // 2. An FrameworkElement's DataContext is an object which implements ITabRegionViewModel
            //      In this situation, the ITabRegionViewModel.Content will auto set to the FrameworkElement itself
            // All other objects will be ignored
            var views = ((IEnumerable<object>)region.Views).Select(p =>
                {
                    if (p is ITabRegionViewModel)
                    {
                        return p;
                    }
                    else if (p is FrameworkElement)
                    {
                        var dataContext = ((FrameworkElement)p).DataContext;
                        if (dataContext != null && dataContext is ITabRegionViewModel)
                        {
                            ((ITabRegionViewModel)dataContext).Content = p;
                            return p;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                }).Where(p => p != null).ToArray();
            // set view
            regionTarget.ItemsSource = views;
        }

        protected override IRegion CreateRegion()
        {
            return new AllActiveRegion();
        }
    }
}